package com.github.pig.admin.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.admin.model.dto.DeptTree;
import com.github.pig.admin.model.entity.SysDept;
import com.github.pig.admin.model.zhgl.building.CommunityBuildingTree;
import com.github.pig.admin.service.sys.SysDeptService;
import com.github.pig.admin.service.sys.SysUserService;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.vo.CommunityInfoBean;
import com.github.pig.common.vo.UserVO;
import com.github.pig.common.web.BaseController;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门管理 前端控制器
 * </p>
 *
 * @author lengleng
 * @since 2018-01-20
 */
@RestController
@RequestMapping("/dept")
public class DeptController extends BaseController {
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 通过ID查询
     *
     * @param id ID
     * @return SysDept
     */
    @GetMapping("/{id}")
    public SysDept get(@PathVariable Integer id) {
        return sysDeptService.selectById(id);
    }


    /**
     * 返回树形菜单集合
     *
     * @return 树形菜单
     */
    @GetMapping(value = "/tree")
    public List<DeptTree> getTree() {
        SysDept condition = new SysDept();
        condition.setDelFlag(CommonConstant.STATUS_NORMAL);
        return sysDeptService.selectListTree(new EntityWrapper<>(condition));
    }

    /**
     * 根据当前登录如返回部门树
     *
     * @return 树形菜单
     */
    @GetMapping(value = "/getTreeByCurrentUser")
    public List<DeptTree> getTreeByCurrentUser(String deptProperty) {
        //当前登陆人所在小区
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        UserVO vo = sysUserService.findUserByUsername(currentUserName);
        return sysDeptService.getTreeByCurrentUser(vo.getDeptId(),deptProperty);
    }

    /**
     * 根据当前登录如返回部门树
     *
     * @return 树形菜单
     */
    @GetMapping(value = "/getCommunitysByCurrentUser")
    public List<SysDept> getCommunitysByCurrentUser() {
        //当前登陆人所在小区
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        UserVO vo = sysUserService.findUserByUsername(currentUserName);
        return sysDeptService.getCommunitysByCurrentUser(vo.getDeptId());
    }

    /**
     * 添加
     *
     * @param sysDept 实体
     * @return success/false
     */
    @PostMapping
    public Boolean add(@RequestBody SysDept  sysDept) {
        return sysDeptService.insertDept(sysDept);
    }

    /**
     * 删除
     *
     * @param id ID
     * @return success/false
     */
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id) {
        return sysDeptService.deleteDeptById(id);
    }

    /**
     * 编辑
     *
     * @param sysDept 实体
     * @return success/false
     */
    @PutMapping
    public Boolean edit(@RequestBody SysDept sysDept) {
        sysDept.setUpdateTime(new Date());
        return sysDeptService.updateDeptById(sysDept);
    }

    /**
     * 分页查询
     *
     * @return 分页对象
     */
    @RequestMapping("/page")
    public Page rolePage(@RequestParam Map<String, Object> params, SysDept bean) {
        EntityWrapper entityWrapper = new EntityWrapper<SysDept>();
        entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        Page<SysDept> page = new Page<SysDept>(Integer.parseInt(params.getOrDefault("page", 1).toString())
                , Integer.parseInt(params.getOrDefault("limit", 10).toString()));
       if(StringUtils.isNotEmpty(bean.getName())){
           entityWrapper.like("name",bean.getName());
       }
       if(bean.getParentId()!=null&&StringUtils.isNotEmpty(bean.getParentId().toString())){
           entityWrapper.eq("parent_id",bean.getParentId());
       }
       if(!CommonConstant.MANAGE_NAME.equals(getUserName())&& CommonConstant.DEPTPROPERTY_PARK.equals(bean.getDeptProperty())){
           List<String> companyIds = sysUserService.findUserByUsername(getUserName()).getCommunityList().stream().map(CommunityInfoBean::getCommunityId)
                   .collect(Collectors.toList());
           //园区没有公司ID
           //.filter(companyId->equals(bean.getParentId()))
           if(companyIds.stream().filter(id->equals(bean.getParentId())).collect(Collectors.toList()).isEmpty()){
               entityWrapper.in("company_id",companyIds);
           }
       }
       entityWrapper.setSqlSelect("profiles,address,dept_id as deptId,company_id as companyId,name,(select b.name from sys_dept b where b.dept_id=`sys_dept`.parent_id ) as parentName,parent_id as parentId,(select label from sys_dict t where t.type='company_type' and t.value=company_type ) as companyTypeName,company_type as companyType, (select label from sys_dict t where t.type='dept_property' and t.value=dept_property ) as deptPropertyName,dept_property as deptProperty, manage_range as manageRange,(select label from sys_dict t where t.type='dept_scop' and t.value=manage_range ) as manageRangeName," +
               "make_time as makeTime,company_scop as companyScop,company_own_size as companyOwnSize, company_lease_size as companyLeaseSize,registered_capital as registeredCapital,company_owner as companyOwner,social_security_number as socialSecurityNumber,employee_number AS employeeNumber");
        return sysDeptService.selectPage(page,entityWrapper);
    }

    /**
     * 获取部门下的子部门
     *
     * @return 分页对象
     */
    @RequestMapping("/getDeptByParent")
    public List<DeptTree> getDeptByParent(SysDept bean) {
//        EntityWrapper entityWrapper = new EntityWrapper<SysDept>();
//        entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
//        if(bean.getParentId()!=null&&StringUtils.isNotEmpty(bean.getParentId().toString())){
//            entityWrapper.eq("parent_id",bean.getParentId());
//        }
//        return sysDeptService.getDeptByParent(entityWrapper,bean.getParentId());
        return sysDeptService.getTreeByCurrentUser(bean.getParentId()==null?"":bean.getParentId().toString(),null);
    }

    @RequestMapping("/getDeptNodeByParent")
    public List<CommunityBuildingTree> getDeptNodeByParent(SysDept bean) {
        EntityWrapper entityWrapper = new EntityWrapper<SysDept>();
        entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        if(bean.getParentId()!=null&&StringUtils.isNotEmpty(bean.getParentId().toString())){
            entityWrapper.eq("parent_id",bean.getParentId());
        }
        if(bean.getDeptProperty()!=null){
            if(CommonConstant.DEPTPROPERTY_COMPANY.equals(bean.getDeptProperty())){
                entityWrapper.eq("dept_property",CommonConstant.DEPTPROPERTY_DEPT);
            }else if(CommonConstant.DEPTPROPERTY_PARK.equals(bean.getDeptProperty())){
                entityWrapper.eq("dept_property",CommonConstant.DEPTPROPERTY_COMPANY);
            }else{
                entityWrapper.eq("dept_property",CommonConstant.DEPTPROPERTY_DEPT);
            }
        }

        UserVO user = sysUserService.findUserByUsername(getUserName());
        if(user==null){
            return null;
        }
        SysDept dept = sysDeptService.selectById(user.getDeptId());
        if(dept!=null){
            entityWrapper.eq("company_id",dept.getCompanyId());
        }
        return sysDeptService.getDeptByParent(entityWrapper,bean.getParentId()==null?"":bean.getParentId().toString());
    }

    @RequestMapping("/getUserNodeByParent")
    public List<CommunityBuildingTree> getUserNodeByParent(SysDept bean) {
        EntityWrapper entityWrapper = new EntityWrapper<SysDept>();
        entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        if(bean.getParentId()!=null&&StringUtils.isNotEmpty(bean.getParentId().toString())){
            entityWrapper.eq("parent_id",bean.getParentId());
        }
        return sysDeptService.getUserNodeByParent(entityWrapper,bean.getParentId()==null?"":bean.getParentId().toString());
    }
}
